package com.zbkj.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.zbkj.dal.entity.product.Parameter;
import com.zbkj.dal.entity.product.ProductParameter;
import com.zbkj.dal.pojo.response.ba.ProductParameterCombineResponse;
import com.zbkj.dal.dao.ProductParameterMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.service.service.ParameterService;
import com.zbkj.service.service.ProductParameterService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品参数 服务实现类
 * </p>
 *
 * @author jhui
 * @since 2023-10-31
 */
@Service
public class ProductParameterServiceImpl extends ServiceImpl<ProductParameterMapper, ProductParameter> implements ProductParameterService {

    @Autowired
    private ParameterService parameterService;

    @Override
    public List<ProductParameterCombineResponse> listProductParameters(Integer productId) {
        LambdaQueryWrapper<ProductParameter> queryWrapper = Wrappers.lambdaQuery(ProductParameter.class);
        queryWrapper.eq(ProductParameter::getProductId, productId);
        List<ProductParameter> list = list(queryWrapper);
        List<ProductParameterCombineResponse> productParameterCombineRespons = Lists.newArrayList();
        if (CollectionUtils.isEmpty(list)) {
            return productParameterCombineRespons;
        }

        List<Integer> params = list.stream().map(m -> m.getParameterId()).distinct().collect(Collectors.toList());
        List<Parameter> parameters = parameterService.listByIds(params);


        for (ProductParameter productParameter : list) {
            Parameter parameter = parameters.stream().filter(p -> ObjectUtils.nullSafeEquals(p.getId(), productParameter.getParameterId()))
                    .findFirst().orElse(null);
            if (parameter == null) {
                continue;
            }
            ProductParameterCombineResponse productParameterCombineResponse = ProductParameterCombineResponse.create(parameter, productParameter.getValue());
            productParameterCombineRespons.add(productParameterCombineResponse);
        }

        return productParameterCombineRespons;
    }

    @Override
    public boolean deleteByProductId(Integer productId) {
        LambdaQueryWrapper<ProductParameter> queryWrapper = Wrappers.lambdaQuery(ProductParameter.class);
        queryWrapper.eq(ProductParameter::getProductId, productId);
        return remove(queryWrapper);
    }
}
